<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import DPlayer from 'dplayer'
import { getVideoInfoList } from '../utils/video'

import { VideoFile, VideoInfo } from '../../../common/types'
import { IpcEvents } from '../../../common/ipcEvents'

const playerRef = ref<HTMLDivElement>()
let player: DPlayer | null = null
const currentVideo = ref<VideoInfo | null>()

const play = (video: VideoInfo): void => {
  if (currentVideo.value?.path !== video.path) {
    currentVideo.value = video
    player?.switchVideo({
      url: `atom:///${video.path}`
    })
    player.play()
  }
}

const pause = (): void => {
  player?.pause()
}

//  拖放,添加历史列表
const handleDrop = async (e: DragEvent): Promise<void> => {
  e.preventDefault()

  const files: VideoFile[] = []
  if (e.dataTransfer) {
    for (const f of e.dataTransfer.files) {
      if (f.type.startsWith('video') || f.name.endsWith('.rpa')) {
        // 只处理视频
        files.push({
          path: f.path,
          name: f.name
        })
      }
    }
  }

  if (files.length) {
    const videoInfoList = await getVideoInfoList(files)
    if (videoInfoList.length === 0) {
      return
    }
    window.electron.ipcRenderer.send(IpcEvents.EV_ADD_VIDEOS, videoInfoList)
  }
}

onMounted(() => {
  if (!player && playerRef.value) {
    player = new DPlayer({
      container: playerRef.value,
      autoplay: false,
      hotkey: true,
      preload: 'metadata',
      video: {
        url: '',
        pic: ''
      }
    })

    // player.on('canplay', () => {
    //   player.play()
    // })
  }
})

onUnmounted(() => {
  if (player) {
    player.destroy()
    player = null
  }
})

defineExpose({
  play,
  pause
})
</script>

<template>
  <div class="player" @drop="handleDrop" @dragenter.prevent @dragover.prevent>
    <div id="dplayer" ref="playerRef"></div>
  </div>
</template>

<style>
@import 'video.js/dist/video-js.css';
@import '../assets/css/player.css';

.player {
  flex: 1;
  overflow: hidden;
}

#dplayer {
  height: 100%;
  widows: 100%;
}
</style>
